package de.hhbk.feedbackmodul.daobeans;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import de.hhbk.feedbackmodul.daointerfaces.TanDaoIF;
import de.hhbk.feedbackmodul.entities.Tan;

@Stateless
public class TanDaoBean implements TanDaoIF {

	@PersistenceContext(unitName = "FeedbackModulEJB")
	private EntityManager manager;
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Tan> getAllTans() throws Exception {
		try
		{
			Query query = manager.createQuery("select t from Tan t", Tan.class);
			return (List<Tan>)query.getResultList();
		}
		catch(Exception e)
		{
			logger.error("Error while reading Tans: "+e.getMessage(), e);
			throw e;
		}
	}

	@Override
	public void createTan(Tan tan) throws Exception {
		try
		{
			manager.persist(tan);
		}
		catch(Exception e)
		{
			logger.error("Error while persisting Tan: "+e.getMessage(), e);
			throw e;
		}
	}

	@Override
	public void updateTan(Tan tan) throws Exception {
		try
		{
			manager.merge(tan);
		}
		catch(Exception e)
		{
			logger.error("Error while updating Tan: "+e.getMessage(), e);
			throw e;
		}
	}

	@Override
	public void deleteTan(Tan tan) throws Exception {
		try
		{
			Tan surveyToDelete = manager.find(Tan.class, tan.getTan_nummer());
			manager.remove(surveyToDelete);
		}
		catch(Exception e)
		{
			logger.error("Error while deleting Tan: "+e.getMessage(), e);
			throw e;
		}
	}

}
